#include "stdafx.h"
#include "LitCScriptParser.h"

namespace Lit
{
	namespace Editor
	{
		namespace Material
		{
			CScriptParser::CScriptParser() : pHead(mRoot){}
			CScriptParser::CScriptParser(const CScriptParser& rk ) : mRoot(rk.mRoot), pHead(mRoot){}
			CScriptParser::~CScriptParser(){}

			CScriptParser::Node& CScriptParser::popHead()
			{
				return (pHead = pHead.parent?*pHead.parent:mRoot);
			}
			CScriptParser::Node& CScriptParser::pushHead( const String &this_name, bool same_level, const String &this_args )
			{
				pHead.name = this_name;
				pHead.args = this_args;
				//Ogre::LogManager::getSingleton().logMessage(String("Creating block '")(this_name)((!this_args.empty())?("' (args: "+this_args+")"):"").str());
				if( same_level )
					pHead = pHead.parent?*pHead.parent:pHead;
				pHead = pHead.createChild();
				return pHead;
			}

			String	CScriptParser::indent( size_t num )
			{
				String ret; for( size_t i=0; i<num; i++ ) ret += " "; return ret;
			}
			String CScriptParser::printNode( Node * node, size_t ind )
			{
				static const size_t tabSize = 20;
				if( !node ) node = &mRoot;
				String ret(String(indent(ind))("Node[")(node->name)("]\r\n"));
				for( auto i=node->nodes.begin(); i!=node->nodes.end(); i++ )
				{
					ret += printNode( node, ind + tabSize );
				}
				return ret;
			}
			void CScriptParser::parse( const String &text )
			{
				if( text.empty() ) return;
				TokenType tok = Char;
				mRoot = Node();
				mRoot.nodes.clear();
				pHead = &mRoot;
				String accu;
				String argstr;
				bool args = false;
				for( size_t i=0; i<text.size(); i++ )
				{
					char c = text.at(i);
					if( c==BlockBeginChar ) tok = BlockBegin;
					else if( c == BlockEndChar ) tok = BlockEnd;
					else if( c == '/' )
					{
						if( i+1 <text.size() && text.at(i+1) == '/' )
							tok = Comment;
					}
					else if( c == SemiColonChar ) tok = SemiColon;
					else tok = Char;

					if( tok == Char )
					{
						accu += c;
					}
					else if( tok == Comment )
					{
						for( i; i<text.size(); i++ )
						{
							char d = text.at(i);
							if( d == '\n' ){
								tok = Char;
								accu += d;
							}
						}
					}
					else if( tok == SemiColon || c == '\n' )
					{
						/*pushHead( accu, true );
						accu = "";*/
					}
					else if( tok == BlockBegin )
					{
						pHead.name = accu;
						accu = "";
					}
					else if( tok == BlockEnd )
					{
					}

				}
			}
			const CScriptParser::Node* CScriptParser::getRootNode() const{ return &mRoot; }
			CScriptParser::Node* CScriptParser::getRootNode() { return &mRoot; }
		};
	};
};